package com.peanut.baby.mvp.search;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.model.PTag;
import com.peanut.baby.util.PrefUtil;
import com.peanut.devlibrary.util.StringUtil;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class SearchHistoryTool {
    public static final int MAX_HISTORY_SIZE = 10;
    public static void saveHistory(String his) {
        List<String> historyRecord = new ArrayList<>();
        String savePrefs = PrefUtil.getString(AppConfig.PrefConfig.PREF_SEARCH_HISTORY);
        if (!StringUtil.isNullOrEmpty(savePrefs)) {
            try {
                JSONArray array = new JSONArray(savePrefs);
                int len = array.length();
                for (int i = 0; i < len; i++) {
                    historyRecord.add(array.getString(i));
                }
            } catch (JSONException e) {

            }
        }

        if (historyRecord == null) {
            historyRecord = new ArrayList<>();
        }
        for (int i = 0; i < historyRecord.size(); i++) {
            if (historyRecord.get(i).equals(his)) {
                historyRecord.remove(i);
                break;
            }
        }
        historyRecord.add(0, his);

        if (historyRecord.size() > MAX_HISTORY_SIZE) {
            historyRecord = historyRecord.subList(0, MAX_HISTORY_SIZE);
        }
        JSONArray array = new JSONArray();
        for (int i = 0; i < historyRecord.size(); i++) {
            array.put(historyRecord.get(i));
        }
        PrefUtil.saveString(AppConfig.PrefConfig.PREF_SEARCH_HISTORY, array.toString());
    }

    public static List<String> getHistoryList() {
        List<String> historyRecord = new ArrayList<>();
        String savePrefs = PrefUtil.getString(AppConfig.PrefConfig.PREF_SEARCH_HISTORY);
        if (!StringUtil.isNullOrEmpty(savePrefs)) {
            try {
                JSONArray array = new JSONArray(savePrefs);
                int len = array.length();
                for (int i = 0; i < len; i++) {

                    historyRecord.add(array.getString(i));
                }
            } catch (JSONException e) {
            }
        }
        return  historyRecord;
    }

    public static List<String> getFreqTags() {
        List<String> historyRecord = new ArrayList<>();
        List<PTag> tags = InitManager.getInstance().getTags();
        if(tags != null && !tags.isEmpty()){
            for(int i=0;i<tags.size();i++){
                historyRecord.add(tags.get(i).name);
            }
        }
        return historyRecord;
    }

    public static void clearHistory(){
        PrefUtil.saveString(AppConfig.PrefConfig.PREF_SEARCH_HISTORY,"");
    }
}
